package com.example.student.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.student.entity.EduCourse;
import com.example.student.entity.SysNotification;
import com.example.student.entity.SysRole;
import com.example.student.entity.SysUser;
import com.example.student.entity.SysUserRole;
import com.example.student.mapper.EduCourseMapper;
import com.example.student.mapper.SysNotificationMapper;
import com.example.student.mapper.SysRoleMapper;
import com.example.student.mapper.SysUserMapper;
import com.example.student.mapper.SysUserRoleMapper;
import com.example.student.model.DashboardDataVO;
import com.example.student.model.NotificationVO;
import com.example.student.service.DashboardService;
import com.example.student.service.NotificationService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DashboardServiceImpl implements DashboardService {

    @Resource
    private SysUserMapper userMapper;
    
    @Resource
    private SysRoleMapper roleMapper;
    
    @Resource
    private SysUserRoleMapper userRoleMapper;
    
    @Resource
    private EduCourseMapper courseMapper;
    
    @Resource
    private SysNotificationMapper notificationMapper;
    
    @Resource
    private NotificationService notificationService;
    
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public DashboardDataVO getDashboardData() {
        DashboardDataVO dashboardData = new DashboardDataVO();
        
        // 统计数据
        Map<String, Integer> stats = new HashMap<>();
        
        // 统计课程总数
        Long courseCount = courseMapper.selectCount(null);
        stats.put("courseCount", courseCount.intValue());
        
        // 统计学生总数
        Long studentRoleId = getStudentRoleId();
        Long studentCount = 0L;
        if (studentRoleId != null) {
            List<Long> studentIds = userRoleMapper.selectList(
                    new LambdaQueryWrapper<SysUserRole>()
                            .eq(SysUserRole::getRoleId, studentRoleId)
            ).stream().map(SysUserRole::getUserId).collect(Collectors.toList());
            
            if (!studentIds.isEmpty()) {
                studentCount = userMapper.selectCount(
                        new LambdaQueryWrapper<SysUser>()
                                .in(SysUser::getId, studentIds)
                );
            }
        }
        stats.put("studentCount", studentCount.intValue());
        
        // 统计教师总数
        Long teacherRoleId = getTeacherRoleId();
        Long teacherCount = 0L;
        if (teacherRoleId != null) {
            List<Long> teacherIds = userRoleMapper.selectList(
                    new LambdaQueryWrapper<SysUserRole>()
                            .eq(SysUserRole::getRoleId, teacherRoleId)
            ).stream().map(SysUserRole::getUserId).collect(Collectors.toList());
            
            if (!teacherIds.isEmpty()) {
                teacherCount = userMapper.selectCount(
                        new LambdaQueryWrapper<SysUser>()
                                .in(SysUser::getId, teacherIds)
                );
            }
        }
        stats.put("teacherCount", teacherCount.intValue());
        
        // 统计通知总数
        Long notificationCount = notificationMapper.selectCount(
                new LambdaQueryWrapper<SysNotification>()
                        .eq(SysNotification::getStatus, 1)
        );
        stats.put("notificationCount", notificationCount.intValue());
        
        dashboardData.setStats(stats);
        
        // 获取最新通知
        LambdaQueryWrapper<SysNotification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysNotification::getStatus, 1)
                .orderByDesc(SysNotification::getPublishTime)
                .last("LIMIT 5");
        
        List<SysNotification> notificationList = notificationMapper.selectList(queryWrapper);
        List<NotificationVO> notificationVOList = notificationList.stream().map(notification -> {
            NotificationVO vo = new NotificationVO();
            BeanUtils.copyProperties(notification, vo);
            
            // 查询发布人信息
            if (notification.getPublishUserId() != null) {
                SysUser user = userMapper.selectById(notification.getPublishUserId());
                if (user != null) {
                    vo.setPublishUserName(user.getRealName() != null ? user.getRealName() : user.getUsername());
                }
            }
            
            // 格式化发布时间
            if (notification.getPublishTime() != null) {
                vo.setPublishTime(notification.getPublishTime().format(DATE_FORMATTER));
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        dashboardData.setNotifications(notificationVOList);
        
        return dashboardData;
    }
    
    /**
     * 获取学生角色ID
     */
    private Long getStudentRoleId() {
        SysRole role = roleMapper.selectOne(
                new LambdaQueryWrapper<SysRole>()
                        .eq(SysRole::getRoleCode, "STUDENT")
        );
        return role != null ? role.getId() : null;
    }
    
    /**
     * 获取教师角色ID
     */
    private Long getTeacherRoleId() {
        SysRole role = roleMapper.selectOne(
                new LambdaQueryWrapper<SysRole>()
                        .eq(SysRole::getRoleCode, "TEACHER")
        );
        return role != null ? role.getId() : null;
    }
} 